<?php

// Gets an environment variable from available sources
function env($key) {
    switch ($key) {
        case 'REQUEST_URI':
            if (empty($_SERVER[$key])) {
                // IIS Mod-Rewrite
                if (isset($_SERVER['HTTP_X_ORIGINAL_URL']))
                    $_SERVER[$key] = $_SERVER['HTTP_X_ORIGINAL_URL'];
                // IIS Isapi_Rewrite
                else if (isset($_SERVER['HTTP_X_REWRITE_URL']))
                    $_SERVER[$key] = $_SERVER['HTTP_X_REWRITE_URL'];
                else {
                    // If root then simulate that no script-name was specified
                    if (empty($_SERVER['PATH_INFO']))
                        $_SERVER[$key] = substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/')) . '/';
                    elseif ($_SERVER['PATH_INFO'] == $_SERVER['SCRIPT_NAME'])
                    // Some IIS + PHP configurations puts the script-name in the path-info (No need to append it twice)
                    $_SERVER[$key] = $_SERVER['PATH_INFO'];
                    else
                        $_SERVER[$key] = $_SERVER['SCRIPT_NAME'] . $_SERVER['PATH_INFO'];
                    // Append the query string if it exists and isn't null
                    if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING']))
                        $_SERVER[$key] .= '?' . $_SERVER['QUERY_STRING'];
                }
            }
        break;
        // Fix empty PHP_SELF
        case 'PHP_SELF':
            if (empty($PHP_SELF))
                $_SERVER[$key] = preg_replace("/(\?.*)?$/", '', env('REQUEST_URI'));
        break;
        // Fix for PHP as CGI hosts that set SCRIPT_FILENAME to something ending in php.cgi for all requests
        case 'SCRIPT_FILENAME':
            if (isset($_SERVER['SCRIPT_FILENAME']) && (strpos($_SERVER['SCRIPT_FILENAME'], 'php.cgi') == strlen($_SERVER['SCRIPT_FILENAME']) - 7))
                $_SERVER[$key] = $_SERVER['PATH_TRANSLATED'];
        break;

    }
    return $_SERVER[$key];
}

// Recursively add slashes from all values in an array
function add_magic_quotes($value) {
    if (is_array($value))
        $return = array_map('add_magic_quotes', $value);
    else
        $return = addslashes($value);
    return $return ;
}

function translate( $text ) {
    global $__language;
    $__language = apply_filters('languages', $__language);
    if( isset( $__language[$text] ) && $__language[$text] !== '' ) {
        return $__language[$text];
    }
    return $text;
}

function __( $text ) {
    return translate( $text );
}
    
function __e( $text ) {
    echo translate( $text );
}

function inflect($name) {
    return strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $name));
}

function uninflect($name) {
    return ucwords(str_replace('_', ' ', $name));
}

function nocache_headers() {
    @ header('Expires: Wed, 11 Jan 1984 05:00:00 GMT');
    @ header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
    @ header('Cache-Control: no-cache, must-revalidate, max-age=0');
    @ header('Pragma: no-cache');
}

function cache_javascript_headers() {
    $expiresOffset = 864000; // 10 days
    header("Content-Type: text/javascript; charset=" . get_bloginfo('charset'));
    header("Vary: Accept-Encoding"); // Handle proxies
    header("Expires: " . gmdate("D, d M Y H:i:s", time() + $expiresOffset) . " GMT");
}

function al_mkdir($target) {
    if (file_exists($target)) {
        if (is_dir($target))
            return true;
        else
            return false;
    }

    // Attempting to create the directory may clutter up our display.
    if (@mkdir($target)) {
        $stat = @ stat(dirname($target));
        $dir_perms = $stat['mode'] & 0007777;  // Get the permission bits.
        chmod($target, $dir_perms);
        return true;
    } else {
        if (is_dir(dirname($target)))
            return false;
    }

    // If the above failed, attempt to create the parent node, then try again.
    if (al_mkdir(dirname($target)))
        return al_mkdir($target);

    return false;
}

function get_option($key) {
    global $aldb;
    $key_value = $aldb->get_var("SELECT `option_value` FROM $aldb->options WHERE `option_name`='$key' LIMIT 1");
    if ($key == 'active_plugins') {
        if (!empty($key_value)) {
            $key_value = unserialize($key_value);
        } else {
            $key_value = array();
        }
    }
    if ($key == 'home_url') {
        if (empty($key_value)) {
            $key_value = get_option('site_url');
        }
    }
    return $key_value;
}

function arlicle_components($component) {
    $componet_file = ARLICLE_COMPONENT . $component . '.php';
    if (file_exists($componet_file)) {
        require_once($componet_file);
    }
}

function arlicle_cut($string, $length = 100, $extra = '...') {
    $string = strip_tags($string);
    $string = preg_replace('/&nbsp;/', ' ', $string);
    $string = preg_replace('/\s+/', ' ', $string);
    preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $string, $info);
    // Remove extra spaces
    $wordscut = '';
    $j = 0;
    for($i=0; $i<count($info[0]); $i++) {
        $wordscut .= $info[0][$i];
        $j = ord($info[0][$i]) > 127 ? $j + 2 : $j + 1;
        if ($j > $length - 3) {
            return $wordscut . $extra;
        }
    }
    return join('', $info[0]);
}

function error_404($die = true) {
    global $html;
    if (!defined('ERROR_404')) {
        define('ERROR_404', true);
    }
    $theme = get_option('template');
    $error_404 = ARLICLE_WWW . 'themes/' . $theme . '/404.php';
    if (file_exists($error_404) && defined('TEMPLATE_DIR')) {
        require $error_404;
    } else {
        echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
            <head><title>404 - Not Found  - Arlicle</title></head>
            <body>
            <h1>404 - Not Found</h1>
            </body>
            </html>';
    }
    if ($die) {
        exit();
    }
}

function al_get_size($size, $unit = null) {
    $kb = 1024; // Kilobyte
    $mb = 1024 * $kb; // Megabyte
    $gb = 1024 * $mb; // Gigabyte
    $tb = 1024 * $gb; // Terabyte
    
    if (!is_numeric($size)) {
        $in_size = intval($size);
        $u = strtoupper(str_replace($in_size, '', $size));
        switch ($u) {
            case 'KB':
            case 'K':
                $size = $in_size * $kb;
                break;
            case 'MB':
            case 'M':
                $size = $in_size * $mb;
                break;
            case 'GB':
            case 'G':
                $size = $in_size * $gb;
                break;
            case 'TB':
            case 'T':
                $size = $in_size * $tb;
                break;
        }
    }
    if (!empty($unit)) {
        $unit = strtoupper($unit);
        switch($unit) {
            case 'KB':
            case 'K':
                $result = round($size / $kb, 2) . ' KB';
                break;
            case 'MB':
            case 'M':
                $result = round($size / $mb, 2) . ' MB';
                break;
            case 'GB':
            case 'G':
                $result = round($size / $gb, 2) . ' GB';
                break;
            case 'TB':
            case 'T':
                $result = round($size / $tb, 2) . ' TB';
                break;
            case 'B':
            case 'BITE':
            default:
                $result = $size;
        }
    } else {
        if($size < $mb) {
            if($size < $kb) {
                $result = $size . ' B';
            } else {
                $result = round($size / $kb, 2) . ' KB';
            }
        } else {
            if($size < $gb) {
                $result = round($size / $mb, 2) . ' MB';
            } else {
                if($size < $tb) {
                    $result = round($size / $gb, 2) . ' GB';
                }else {
                    $result = round($size / $tb, 2) . ' TB';
                }
            }
        }
    }
    return $result;
}

function al_redirect($url) {
    $location = Router::get_url() . $url;
    header("Location: $location");
    exit();
}

function unique_id($length = 16, $extra = 'c') {
    $val = microtime();
    $val = md5(get_option('site_url') . $val . $extra);
    return substr($val, 0, $length);
}

function is_arlicle_installed() {
    global $aldb;
    $site_url = $aldb->get_var("SELECT option_value FROM $aldb->options WHERE option_name='site_url'");
    $installed = empty($site_url) ? false : true;
    return $installed;
}

function arlicle_die($message, $title = '') {
    $base = str_replace('index.php', '', env('SCRIPT_NAME'));
?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Arlicle </title>
<link rel="stylesheet" href="<?php echo $base; ?>arlicle/app/webroot/css/error.css" type="text/css" media="all" />
</head>
<body id="error-page">
<h1 id="logo"><img alt="Arlicle" src="<?php echo $base; ?>arlicle/app/webroot/img/logo_login.gif" /></h1>
<?php echo $message; ?>
</body>
</html>
<?php
    die();
}

function admin_url($url) {
    return Router::get_url() . '/' . ARLICLE_ADMIN . $url;
}

function admin_link($title, $url, $other = '') {
    return '<a href="' . admin_url($url) . '" ' . $other . '>' . $title . '</a>';
}

function is_email($user_email) {
    $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
    if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false) {
        if (preg_match($chars, $user_email)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function arlicle_url($url) {
    return get_option('site_url') . Router::get_url() . $url;
}

?>
